import classnames from 'classnames'
import type { FC } from 'react'
import React, { useState } from 'react'
import { withNativeProps } from '../../../src/utils/native-props'
import type { ComponentProps, ImageMode } from '../../global/common-style'

export type ImageLoadProps = {
  /** src
   *  @type {string}
   */
  src: string
  /** defaultSource,不提供则不会替换
   *  @type {string}
   */
  defaultSource?: string
  /** mode
   *  @memberof Mode
   */
  mode?: keyof ImageMode
  /** lazyLoad
   *  @type {boolean}
   *  @default true
   */
  lazyLoad?: boolean
  /** onClick
   *  @type {function}
   */
  onClick?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
} & ComponentProps

export const ImageLoad: FC<ImageLoadProps> = (props) => {
  const {
    src,
    defaultSource,
    lazyLoad = true,
    className,
    style,
    mode,
    onClick,
  } = props
  const [finishFlag, setFinishFlag] = useState(false)

  return withNativeProps(
    props,
    <div
      onClick={(event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        onClick?.(event)
      }}
    >
      {!finishFlag && (
        <img
          src={defaultSource}
          className={classnames(className)}
          style={{ ...style, objectFit: mode }}
          loading={lazyLoad ? 'lazy' : 'eager'}
        />
      )}
      <img
        src={src}
        className={className}
        style={
          finishFlag
            ? { ...style, opacity: 1, objectFit: mode }
            : { opacity: 0, width: 0, height: 0, objectFit: mode }
        }
        loading={lazyLoad ? 'lazy' : 'eager'}
        onLoad={() => {
          setFinishFlag(true)
        }}
      />
    </div>
  )
}
